<script setup>
import { ref, createVNode,defineAsyncComponent } from "vue";
import {
  CloseOutlined,
  InfoCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import request from "@/common/utils/request";
import utils from "@/common/utils/utils";
import { message } from "ant-design-vue";
import addArea from "../modules/AddArea.vue";
import store from "@/store/index";
import { Modal } from "ant-design-vue";
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});
const AccountManage = defineAsyncComponent(() => import('@/views/home/accountCenter/accountManage.vue'))

const emit = defineEmits(["update:visible", "logined", "startSync"]);
const appName =ref('');

const appPath = import.meta.env.VITE_APP_SHORT_NAME;
const appVersion = import.meta.env.VITE_APP_VERSION;
const electron =  import.meta.env.ELECTRON
const area = ref({});
const accountManageRef = ref();
const aiConfig = ref();
const appKey = ref();
const addAccountVisible = ref(false);
const downloadVisible = ref(false);
const appConfig = ref([]);
const authVisible = ref(false);
const authCancel = ref(false);
const isContinueBind = ref(true);
const areaVisible = ref(false);
const openAiPlatmor = ref({
  kuaishou: true,
  bilibili: true,
  tiktok: true,
});
const { result } = await request.get(
  "/work_ai",
  "/org/platform/account/shotStackList",
  { filterShow: 1 }
);

appConfig.value = result;
aiConfig.value = await store.dispatch("getAiConfig");

const onClose = () => {
  emit("update:visible", false);
};
const onAddAccount = (item) => {
  appKey.value = item.key;
  if (!item.login_url || item.developing == 1) {
    return message.warning({
      content: () => "功能开发中",
      class: "custom-class",
      style: {
        marginTop: "20vh",
      },
      duration: 1,
    });
  }
  const env = import.meta.env.ELECTRON;
  if (env) {
    // 客户端
    areaVisible.value = true;
  } else {
    store.dispatch("getAiConfig").then((aiConfig) => {
      appName.value = aiConfig.site_name
    })
       // 网页端
    downloadVisible.value = true;
  
   
  }
};

// 用户代理
const userAgent = ref('')
// 代理
const proxy = ref('')

const onConfirmArea = (params) => {
  
  area.value = params.area;
  proxy.value = params.proxy;
  userAgent.value = params.userAgent;
  // if(appKey.value == 'tiktok'){
  //   areaVisible.value = false;
  //   authVisible.value = true;
  //   return
  // }
  areaVisible.value = false;
  addAccountVisible.value = true;
};
let platformInfo = ref(null);
const onAuthAccount = (e) => {
  if (e.developing == 1) {
    return message.warning({
      content: () => "功能开发中",
      class: "custom-class",
      style: {
        marginTop: "20vh",
      },
      duration: 1,
    });
  }
  appKey.value = e.key;
  const env = import.meta.env.ELECTRON;
  if (env) {
    // 客户端-app
    return
  } else {
    // 网页端
    downloadVisible.value = false;
    platformInfo.value = e;
    // if(e.key == 'tiktok'){
    //   areaVisible.value = true;
    //   return
    // }
    authVisible.value = true;
  }
};
const AuthLoading = ref(false);
// 前往授权
const handleAuth = (e) => {
  if (!isContinueBind.value) {
    //TODO 这里需要判断绑定的上限，提示语：抱歉您当前可绑定账号数量已达到上限,无法新增
    authVisible.value = false;
    return message.error("抱歉您当前可绑定账号数量已达到上限,无法新增");
  }
  AuthLoading.value = true;
  let params = {
    source: platformInfo.value.key,
  }
  // if(appKey.value == 'tiktok'){
  //   params.area =  area.value
  // }
  request
    .post("/work_ai", "/org/platform/account/user/authorize", params)
    .then((res) => {
      if (res.result.url) {
        window.open(res.result.url, "_blank"); // 打开新窗口
        authVisible.value = false;
      } else {
        return message.warning("获取授权链接失败");
      }
      AuthLoading.value = false;
    })
    .catch((err) => {
      console.log(err);
    })
    .finally(() => {
      authVisible.value = false;
      AuthLoading.value = false;
    });
};

const onAuthCancel = () => {
  console.log("取消网页授权");
  authVisible.value = false;
};

const onCancel = () => {
  addAccountVisible.value = false;
  appKey.value = "";
};

const onError = () => {
  onCancel()
}

const downloadCancel = () => {
  downloadVisible.value = false;
  appKey.value = "";
};
const onAccountLogined = async (res) => {
  let app = appConfig.value.find((item) => item.key === appKey.value);
  let successRes = {};
  if (!app.is_scan_authorize) {
    try {
      let params = {
        org_id: utils.getOrgId(),
        header: res.headers,
        source: appKey.value,
        team_id: store.state.user.teamId,
        area: area.value,
      }
      if(appKey.value=='douyin'){
        params.is_douyin_org_main = res.loginType == 'org'? 1 : 0
      }
      successRes = await request.post("/work_ai", "/org/platform/account/user/sync", params);
      
    } catch (e) {
      console.log(e, "error");
      onCancel();
      emit("logined", {
        ...res,
        appKey: appKey.value,
      }); 
      message.error(e.msg);
      return 
    }
  }

  onCancel();
  message.success("授权成功");

  emit("logined", {
    ...res,
    appKey: appKey.value,
  }); 
  if (successRes?.result?.orgResult?.status == 'process'&& successRes?.result?.orgResult?.sync_task_id) {
    emit("startSync", {
      sync_task_id: successRes?.result?.orgResult?.sync_task_id,
      nickname: successRes?.result?.nickname,
      source_txt: successRes?.result?.source_txt,
    });
  }
};
</script>

<template>
  <a-modal
    :visible="visible"
    title="选择添加账号的平台"
    destroyOnClose
    centered
    :width="700"
    @cancel="onClose"
    :footer="null"
    :zIndex="1002"
  >
    <div class="modal-content">
      <div v-for="item in appConfig" :key="item.key">
        <!-- 网页授权 -->
        <div
          v-if="item.key in openAiPlatmor"
          class="app-item"
          @click="onAuthAccount(item)"
          :class="electron && item.is_scan_authorize ? 'not-allowed' :''"
        >
          <a-tooltip color="red">
            <template #title>请前往网页端进行授权！</template>
            <template v-if="electron && item.is_scan_authorize">
              <div class="app-item-img">
                <img :src="item.image" class="app-img" />
              </div>
              <div class="app-item-txt">{{ item.value }}</div>
            </template>
          </a-tooltip>
          <template v-if="!electron && item.is_scan_authorize">
            <div class="app-item-img">
                <img :src="item.image" class="app-img" />
              </div>
              <div class="app-item-txt">{{ item.value }}</div>
          </template>
        </div>
        <!-- app扫码授权 -->
        <a-popover v-else>
          <div class="app-item-img" @click="onAddAccount(item)">
            <img :src="item.image" class="app-img" />
          </div>
          <div class="app-item-txt">{{ item.value }}</div>
        </a-popover>
      </div>
    </div>
  </a-modal>

  <a-modal
    :visible="downloadVisible"
    :width="450"
    closable
    @cancel="downloadCancel"
    :footer="null"
    centered
    :forceRender="true"
    :zIndex="1003"
    wrapClassName="download-modal"
    title="请前往客户端添加账号绑定"
  >
    <div class="text-center">
      <h2 style="color: #162d5b; font-size: 24px">
        下载{{ appName }}客户端
        <span style="font-size: 10px; color: #999">v{{ appVersion }}</span>
      </h2>
      <div style="color: #abb0bd; font-size: 20px">
        同时支持 Windows,MacOS 版本
      </div>
      <div class="down-list">
        <div class="down-item">
          <a
            download=""
            :href="`${aiConfig?.shotack_desktop_path}/${appPath}-${appVersion}-setup.exe?version=${appVersion}`"
            target="_blank"
          >
            <div>
              <img
                src=""
                alt=""
              />
            </div>
            <span>Windows 10 及以上</span>
          </a>
        </div>

        <div class="down-item">
          <a
            download=""
            :href="`${aiConfig?.shotack_desktop_path}/${appPath}-${appVersion}.dmg?version=${appVersion}`"
            target="_blank"
          >
            <div>
              <img
                src=""
                alt=""
              />
            </div>
            <span>MacOS 11 及以上</span>
          </a>
        </div>
      </div>
    </div>
  </a-modal>

  <a-modal
    :visible="addAccountVisible"
    width="90vw"
    wrapClassName="account-modal"
    :closable="false"
    @cancel="onCancel"
    :footer="null"
    style="height: 90vh; top: 5vh; padding-bottom: 0px"
    :forceRender="true"
    :zIndex="1003"
  >
    <div class="w-full h-full">
      <Suspense>
        <AccountManage
          :app-key="appKey"
          :area="area"
          :proxy="proxy"
          :userAgent="userAgent"
          ref="accountManageRef"
          @logined="onAccountLogined"
          @onError="onError"
        >
          <template #header_after>
            <CloseOutlined class="cursor-pointer" @click="onCancel" />
          </template>
        </AccountManage>
      </Suspense>
    </div>
  </a-modal>

  <a-modal
    :visible="authVisible"
    :width="620"
    closable
    @cancel="onAuthCancel"
    centered
    :forceRender="true"
    :zIndex="1003"
    style="border-radius: 10px; overflow: hidden"
    wrapClassName="download-modal"
  >
    <template #title>
      <div style="width: 100%; font-size: 18px">
        <info-circle-outlined
          style="color: #2878ff; margin-right: 6px"
        />新增授权
      </div>
    </template>
    <div>
      <h3 style="color: #162d5b; font-size: 18px; font-weight: 600">
        授权即代表您同意通过{{ appName }}：
      </h3>
      <p style="font-size: 16px; margin-top: 20px">
        <check-circle-outlined style="color: #18a058" />
        往您的{{
          platformInfo?.value
        }}账号发布公开作品（发布内容、频次由您通过{{ appName }}系统操作设置）
      </p>
      <p style="font-size: 16px">
        <check-circle-outlined style="color: #18a058" />
        获取您的{{ platformInfo?.value }}账号信息、视频数据、评论等
      </p>
      <div style="margin-top: 10px; font-size: 12px">
        <div style="color: #b33d55; font-weight: 500">
          <p>重要提醒：</p>
          <p>
            1.
            生成的授权链接仅支持在PC端打开{{ appKey == 'tiktok' ?'。':'，'}} <span v-if="appKey != 'tiktok'">然后使用手机扫码授权，直接使用手机打开将授权失败（无法授权视频发布的能力）</span> 
          </p>
          <p>
            2.“前往您的{{
              platformInfo?.value
            }}账号发布公开作品”权限，仅支持同时授权给1个平台，若此账号授权给其它平台此能力将失效，视频发布将失败！
          </p>
        </div>
      </div>
    </div>

    <template #footer>
      <a-button key="back" @click="onAuthCancel">取消</a-button>
      <a-button
        type="primary"
        key="submit"
        @click="handleAuth"
        :loading="AuthLoading"
        >确定</a-button
      >
    </template>
  </a-modal>
  <!-- 添加/编辑账号所在地区 -->
  <addArea v-model:visible="areaVisible" :id="null" :appKey="appKey"  @success="onConfirmArea"></addArea>
</template>

<style lang="less" scoped>
.modal-content {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.app-item {
  cursor: pointer;

  &.not-allowed{
    cursor: not-allowed;
  }
}

.app-item-img {
  display: flex;
  width: 50px;
  height: 50px;
}

.app-img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 5px;
}

.app-item-txt {
  display: flex;
  justify-content: center;
  line-height: 40px;
}
.disabled-txt {
  color: #ccc;
}
</style>

<style lang="less">
.account-modal .ss-modal-body {
  padding: 0;
}

.account-modal .ss-modal-content {
  height: 100%;

  .ss-modal-body {
    height: 100%;
  }
}

.download-modal {
  .down-list {
    display: flex;
    flex-flow: row;
    justify-content: space-around;
    height: 148px;
    width: 100%;
    margin-top: 20px;
    padding: 0 20px;

    .down-item {
      -webkit-user-select: none;
      -moz-user-select: none;
      user-select: none;
      cursor: pointer;
      box-shadow: 0 2px 16px rgba(28, 76, 186, 0.08);
      text-align: center;
      width: 148px;
      height: 148px;
      border-radius: 4px;

      > a {
        width: 100%;
        height: 100%;
        padding: 24px 0;
        display: inline-block;
      }

      div {
        padding-bottom: 12px;
      }
    }
  }

  .pc-list {
    display: flex;
    flex-flow: row;
    justify-content: space-around;
    height: 148px;
    width: 100%;
    margin-top: 20px;
    padding: 0 20px;
    color: red;

    .down-item {
      -webkit-user-select: none;
      -moz-user-select: none;
      user-select: none;
      cursor: pointer;
      box-shadow: 0 2px 16px rgba(28, 76, 186, 0.08);
      text-align: center;
      // width: 148px;
      height: 148px;
      border-radius: 4px;

      > a {
        width: 100%;
        height: 100%;
        padding: 24px 0;
        display: inline-block;
      }

      div {
        padding-bottom: 12px;
      }
    }
  }
}
</style>
